#!/usr/bin/python

import os
import sys
import subprocess

PASSPHRASE = "./passphrase.txt"

cryptcmd = [ "/usr/bin/aespipe", "-P", PASSPHRASE ]

if len(sys.argv) <> 3:
	print "Usage: %s input output" % sys.argv[0]
	exit(0)

input = sys.argv[1]
output = sys.argv[2]

if not os.path.exists(PASSPHRASE):
	print "passphrase file '%s' not exists" % PASSPHRASE
	exit(0)

if not os.path.exists(input):
	print "input file '%s' not exists" % input
	exit(0)

if os.path.exists(output):
	print "output file '%s' already exists, please remove it first" % output
	exit(0)
try:
	f1 = open(input, 'r')
except IOError:
	print "Can't open file '%s'" % input
	exit(0)

try:
	f2 = open(output, 'w')
except IOError:
	print "Can't create output file '%s'" % output
	exit(0)

buf = f1.read()
l = len(buf)
print "Read %d bytes from %s" % (l, input)

if l > (1024*100):
	print "Input file is too big, bail out!"
	exit(0)

# Unbuffered
p1 = subprocess.Popen(cryptcmd, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

p1.stdin.write(buf)
print "Write to pipe..."

buf2 = p1.communicate()[0]
print "Read %d bytes from pipe" % len(buf2)

f2.write(buf2)
print "Write to file ..."

print "Done."

exit(0)
